<template>
  <div class="check-list">
    <div class="check-sum">
      <eagle-notice-bar v-if="!isRead" color="#323233" background="#fff">
        当前已检查{{ totalnum }}项,其中不符合{{ noNum }}项
      </eagle-notice-bar>
    </div>
    <div class="check-content">
      <van-collapse v-model="activeNames" accordion>
        <template v-for="(item, index) in List">
          <van-collapse-item :name="index + 1" :key="index">
            <template #title>
              <div class="checklist-title">
                <img
                  class="title-logo"
                  src="@/assets/Images/AppIcon/fragment_noticetype_3.png"
                  alt=""
                />
                {{ item.DetailItemName }} | 共{{ item.children.length }}个项目
              </div>
            </template>

            <div
              v-for="(innerItem, innerIndex) in item.children"
              :key="innerIndex"
            >
              <div class="color-gray1">
                {{ innerIndex + 1 }}、{{ innerItem.DetailItemName }}
              </div>
              <div v-if="!isRead" class="accord-btns mt-10" >
                <div
                  class="accord-btn"
                  @click="handleClick(index, innerIndex, 'Y')"
                  :class="
                    innerItem.CheckResult == 'Y' && innerItem.checked
                      ? 'active'
                      : ''
                  "
                >
                  符合
                </div>
                <div
                  class="accord-btn"
                  @click="handleClick(index, innerIndex, 'N')"
                  :class="
                    innerItem.CheckResult == 'N' && innerItem.checked
                      ? 'inconformity'
                      : ''
                  "
                >
                  不符合
                </div>
                <div
                  class="accord-btn"
                  @click="handleClick(index, innerIndex, 'NA')"
                  :class="
                    innerItem.CheckResult == 'NA' && innerItem.checked
                      ? 'not-applicable'
                      : ''
                  "
                >
                  不适用
                </div>
              </div>
              <eagle-form
                v-if="
                  (innerItem.CheckResult == 'Y' ||
                    innerItem.CheckResult == 'NA') &&
                  innerItem.checked
                "
              >
                <div class="inconformity-list">
                  <eagle-row>
                    <eagle-col span="4" offset="1">备注</eagle-col>
                    <eagle-col span="24">
                      <eagle-input
                        v-model="innerItem.Remarks"
                        rows="3"
                        autosize
                        type="textarea"
                        maxlength="50"
                        placeholder="请输入"
                        :isCustom="false"
                      ></eagle-input>
                    </eagle-col>
                  </eagle-row>
                </div>
              </eagle-form>
              <eagle-form
                v-if="innerItem.CheckResult == 'N' && innerItem.checked"
              >
                <div class="inconformity-list">
                  <div>
                    <eagle-image-uploader
                      class="ml-10"
                      :images.sync="innerItem.Attachs"
                    ></eagle-image-uploader>
                    <div>
                      <div>
                        <van-field
                          class="input_text"
                          label="隐患区域"
                          input-align="right"
                        >
                          <template #input>
                            <div
                              style="display: flex; color: #1296db"
                              @click="showDangerArea(index, innerIndex)"
                            >
                              <img
                                src="@/assets/Images/AppIcon/icon_danger_select.png"
                                alt=""
                              />
                              选择隐患区域
                            </div>
                          </template>
                        </van-field>
                      </div>
                      <van-field v-model="innerItem.HiddenDangerArea" />
                    </div>
                    <div>
                      <eagle-input
                        title="隐患描述"
                        v-model="innerItem.HiddenDangerDesc"
                        rows="3"
                        autosize
                        type="textarea"
                        :isMust="true"
                        placeholder=""
                        multiRow
                        :isCustom="false"
                      ></eagle-input>
                    </div>
                    <template v-if="isManager">
                      <eagle-radio-group
                        class="input_text"
                        label="隐患等级"
                        required
                        direction="horizontal"
                        v-model="innerItem.DangerLevel"
                        :dataSource="List[0].DangerLevels"
                        v-if="innerItem.DangerUseLevel"
                      >
                      </eagle-radio-group>
                      <eagle-input
                        name="CheckTypeName"
                        label="隐患分类"
                        :value="innerItem.LGDFullName"
                        required
                        islink
                        readonly
                        @click="showDangerType(index, innerIndex)"
                        placeholder="请选择"
                      ></eagle-input>
                      <!-- 单选框 -->
                      <eagle-radio-group
                        v-model="innerItem.HiddenDangerType"
                        label="隐患性质"
                        required
                        name="HiddenDangerType"
                        :dataSource="hiddenDangerTypes"
                        direction="horizontal"
                        v-if="innerItem.DangerUseHiddenDangerType"
                      >
                      </eagle-radio-group>

                      <!-- <van-field
                        v-if="isJG"
                        class="input_text"
                        :value="getCorrectUserText(innerItem)"
                        label="整改部门/人"
                        placeholder="请选择"
                        required
                        readonly
                        @click="showDeprtartmentUser(index, innerIndex)"
                      >
                        <template #right-icon
                          ><van-icon name="arrow"
                        /></template>
                      </van-field> -->
                      <!-- 日期 Date-->
                      <date-picker
                        label="整改期限"
                        :required="innerItem.IsMustSubCorrectiveDate"
                        showFastSelect="true"
                        :date.sync="innerItem.CorrectiveDate"
                      ></date-picker>
                    </template>
                  </div>
                </div>
              </eagle-form>
              <van-divider />
            </div>
          </van-collapse-item>
        </template>
      </van-collapse>
    </div>
    <template v-if="isManager&&!isRead"">
      <div class="bottom-buttons">
        <van-button
          class="save-btn"
          type="primary"
          @click="SaveCheckTaskTemplateDetails('2')"
          >提交</van-button
        >
        <van-button
          class="save-btn"
          v-if="!ctCode"
          @click="SaveCheckTaskTemplateDetails('1')"
          type="info"
          >暂存</van-button
        >
        <van-button
          class="save-btn"
          v-if="ctCode"
          @click="SaveCheckTaskTemplateDetails('0')"
          type="info"
          >临时保存</van-button
        >
        <van-button
          class="save-btn"
          v-if="ctCode"
          @click="ClearCheckTaskTemplateDetails"
          type="warning"
          >重置</van-button
        >
      </div>
    </template>
    <template v-else>
      <div class="bottom-buttons" v-if="!isRead">
        <van-button
          class="submit-button"
          type="primary"
          @click="SaveCheckTaskTemplateDetails('2')"
          >提交至管理员</van-button
        >
        <van-button
          class="save-btn"
          v-if="!ctCode"
          @click="SaveCheckTaskTemplateDetails('1')"
          type="info"
          >暂存</van-button
        >
        <van-button
          class="save-btn"
          v-if="ctCode"
          @click="SaveCheckTaskTemplateDetails('0')"
          type="info"
          >临时保存</van-button
        >
   
      </div>
    </template>
    <!-- 隐患区域 -->
    <danger-area-dialog
      :multi="false"
      :show.sync="showDangerAreaDialog"
      @callback="onDangerAreaCallback"
    ></danger-area-dialog>
    <!-- 隐患分类 -->
    <danger-type-dialog
      v-model="showDangerTypeDialog"
      @callback="onDangerTypeCallback"
    >
    </danger-type-dialog>
    <!-- 部门，人 -->
    <department-and-user-dialog
      v-model="showDepartmentAndUserDialog"
      @callback="onUserCallback"
    ></department-and-user-dialog>
    <user-choose-dialog
      @callback="onUserCallback"
      :show.sync="showUserChooseDialog"
    ></user-choose-dialog>
    <van-dialog v-model="messageShow" title="询问" showConfirmButton showCancelButton @confirm="save2">
      <div>{{'还有'+count+'项目未检查，具体如下：'}}</div>
      <div v-for="item in messageArrayFor4">{{item}}</div>
      <div>......确定要继续操作吗?</div>
    </van-dialog>
  </div>
</template>

<script>
import {
  getDetailTemplateData,
  saveCheckTaskTemplateDetailsJG,
} from "@/api/dangerCheckTaskDetail";
import { mapGetters } from "vuex";
import DangerTypeDialog from "@/views/components/danger/dangerTypeDialog.vue";
import DangerAreaDialog from "@/views/components/danger/dangerAreaDialog.vue";
import DepartmentAndUserDialog from "@/views/components/department/departmentUserChooseDialog.vue";
import UserChooseDialog from "@/views/components/user/userChooseDialog.vue";
export default {
  components: {
    DangerTypeDialog,
    DangerAreaDialog,
    DepartmentAndUserDialog,
    UserChooseDialog,
  },
  data() {
    return {
      tCode: "",
      List: [],
      activeNames: 1,
      data: {},
      idx: "",
      show: false,
      innerIndex: "",
      index: "",
      CompanyCode: this.$route.query.CompanyCode || "",
      ctCode: this.$route.query.ctCode || "",
      data: {},
      saveOp: "",
      totalnum: 0,
      noNum: 0,
      keyObject: {},
      formData: [],
      showDangerAreaDialog: false,
      showDangerTypeDialog: false,
      showDepartmentAndUserDialog: false,
      DangerSimpleType: "",
      showUserChooseDialog: false,
      hiddenDangerTypes:[{ID:"1",Name:"一般隐患"},{ID:"2",Name:"重大隐患"}],
      isJG:false,
      isRead:false,
      messageArray:[],
      count:0,
      messageShow:false,
      continue:false
    };
  },
  created() {
    if(this.$store.state.CompanyType == "JG") {
      this.isJG = true
    }
    this.isRead=this.$route.query.isRead?true:false
    if (this.$route.query.tCode) {
      this.tCode = this.$route.query.tCode;
      this.tRand = this.$route.query.tRand;
      this.activeNames = 1;
      this.getDetail();
    }
  },
  computed: {
    ...mapGetters(["roles"]),
    isManager: {
      get() {
        return (
          // this.roles.indexOf("admin") != -1 || this.DangerSimpleType == "A"
          true
        );
      },
    },
    isSimple: {
      get() {
        return this.DangerSimpleType == "A";
      },
    },
    messageArrayFor4() {
      return this.messageArray.slice(0, 4)
    }
  },
  methods: {
    close(type) {
      if (type) {
        const saveOp = this.saveOp;
        saveCheckTaskTemplateDetailsJG(
          this.formData,
          saveOp,
          this.CompanyCode
        ).then((res) => {
          this.$router.go(-1);
        });
      }
      this.show = false;
    },
    getCorrectUserText(item) {
      if (item.CorrectiveDeptName || item.CorrectiveChnName) {
        if (item.CorrectiveChnName && item.CorrectiveDeptName) {
          return item.CorrectiveDeptName + "-" + item.CorrectiveChnName;
        } else if (item.CorrectiveChnName) {
          return item.CorrectiveChnName;
        } else {
          return item.CorrectiveDeptName;
        }
      }
      return "";
    },
    getDetail() {
      let params = {
        tCode: this.tCode,
        tRand: this.tRand,
        ctCode: this.ctCode,
        CompanyCode: this.CompanyCode,
      };
      getDetailTemplateData(params).then((res) => {
        let newList = [];
        this.DangerSimpleType = "";
        res.data.map((item, index) => {
          let innerobj = {};
          if (item.ID === -1) {
            innerobj = item;
            innerobj.children = [];
            res.data.map((innerItem, innerIndex) => {
              if (innerItem.SEQ === item.SEQ && innerItem.ID != -1) {
                innerItem.checked = innerItem.CheckResult;
                innerItem.HiddenDangerType = innerItem.HiddenDangerType || "1";
                if (this.$route.query.areaCode) {
                  innerItem.HiddenDangerAreaCode = this.$route.query.areaCode;
                  innerItem.IsAssignedArea = true;
                }
                if (this.$route.query.areaName) {
                  innerItem.HiddenDangerArea = this.$route.query.areaName;
                }
                if (this.$route.query.areaType) {
                  innerItem.HiddenDangerAreaType = this.$route.query.areaType;
                }
                if (this.$route.query.areaNo) {
                  innerItem.HiddenDangerAreaNo = this.$route.query.areaNo;
                }
                if (innerItem.DangerSimpleType == "A") {
                  this.DangerSimpleType = "A";
                }
                innerobj.children.push(innerItem);
              }
            });
            newList.push(innerobj);
          }
        });
        this.List = newList;
        this.calcNum();
      });
    },
    // 点击符合、不符合
    handleClick(index, innerIndex, CheckResult) {
      this.List.forEach((item, idx) => {
        if (index == idx) {
          item.children.forEach((v, i) => {
            if (i == innerIndex) {
              if (v.CheckResult == CheckResult) {
                v.checked = !v.checked;
                v.CheckResult = "";
              } else {
                v.checked = true;
                v.CheckResult = CheckResult;
                if(CheckResult=="N"){
                  v.HiddenDangerType=v.HiddenDangerType||"1";
                  v.DangerLevel = v.DangerLevel||(this.List[0].DangerLevels.length>0?this.List[0].DangerLevels[0].ID:"")
                }
              }
            }
          });
        }
      });
      this.calcNum();
    },
    calcNum() {
      let totalnum = 0;
      let noNum = 0;
      this.List.map((item, idx) => {
        item.children.map((innerItem, innerIds) => {
          if (innerItem.CheckResult != "" && innerItem.CheckResult != null) {
            console.log("innerItem.CheckResult", innerItem.CheckResult);
            totalnum++;
          }
          if (innerItem.CheckResult == "N") {
            noNum++;
          }
        });
      });
      this.totalnum = totalnum;
      this.noNum = noNum;
    },
    // 保存
    SaveCheckTaskTemplateDetails(saveOp) {
      this.saveOp = saveOp;
      let newArr = [];
      var message = "";
      this.count=0
      this.mesageArray=[]
      this.List.forEach((item) => {
        if (item.children) {
          item.children.map((item1,index1) => {
            console.log(item1.CheckResult)
            if (item1.CheckResult == "N" && saveOp == "2") {
              if (!item1.HiddenDangerArea && item1.LGDType == "2") {
                message =
                  message +
                  "[" +
                  item1.DetailTitle +
                  "]的第" +
                  item1.DetailItemOrder +
                  "项是现场管理类隐患，必须填写隐患区域";
              }
              if (!item1.HiddenDangerDesc) {
                message =
                  message +
                  "[" +
                  item1.DetailTitle +
                  "]的第" +
                  item1.DetailItemOrder +
                  "项必须填写隐患描述";
              }
              if (this.isManager) {
                if (!item1.LGDCode) {
                  message =
                    message +
                    "[" +
                    item1.DetailTitle +
                    "]的第" +
                    item1.DetailItemOrder +
                    "项必须选择隐患分类";
                }
                      if (this.isManager) {
                if (!item1.CorrectiveDate) {
                  message =
                    message +
                    "[" +
                    item1.DetailTitle +
                    "]的第" +
                    item1.DetailItemOrder +
                    "项必须选择整改期限";
                }}
                // if (!item1.CorrectiveDeptCode && !item1.CorrectiveUserName) {
                //   message =
                //     message +
                //     "[" +
                //     item1.DetailTitle +
                //     "]的第" +
                //     item1.DetailItemOrder +
                //     "项必须选择整改部门/人";
                // }
              }
            }else if(!item1.CheckResult){
              
                this.count+=1
                this.messageArray.push("["+item.TName+"]的第"+(index1+1)+"项未检查")
            }
            item1.ID = 0;
            newArr.push(item1);
          });
        }
      });
      if (message) {
        return this.$toast(message);
      }

      const hasResult = newArr.filter((v) => v.CheckResult);
      const noResult = newArr.filter((v) => !v.CheckResult && !v.checked);
      if (hasResult.length == 0) {
        this.$toast("未包含任何需暂存/提交的检查记录");
        // this.show = true;
        // this.data = {
        //   List: this.List,
        //   num: noResult.length,
        // };
        return;
      }
      let formData = [];
      newArr.map((item) => {
        if (item.CheckResult) {
          item.CTCode = this.ctCode;
          console.log(item, "item");

          formData.push(item);
        }
      });
      this.formData = formData;
        console.log(this.continue)
      if((saveOp=='1'||saveOp=='2')&&this.count>0 && !this.continue){
        this.messageShow=true
      }else{  
        saveCheckTaskTemplateDetailsJG(formData, saveOp, this.CompanyCode).then(
        (res) => {
          this.$router.go(-1);
        }
      );
      }
      this.continue=false
    
    },
    save2(){
      this.continue=true
      this.SaveCheckTaskTemplateDetails(this.saveOp)
    },
    //隐患分类
    showDangerType(index, innerIndex) {
      this.keyObject = {
        index,
        innerIndex,
      };
      this.showDangerTypeDialog = true;
    },
    onDangerTypeCallback(item) {
      if (item) {
                
        const index = this.keyObject.index;
        const innerIndex = this.keyObject.innerIndex;

        this.List.forEach((item1, idx) => {
          if (index == idx) {
            item1.children.forEach((v, i) => {
              if (i == innerIndex) {
                v.LGDCode = item.DCode;
                v.LGDName = item.DName;
                v.LGDType = item.DType;
                v.LGDTypeName = item.DTypeName;
                v.LGDFullName = item.DFullName;
              }
            });
          }
        });
      }
      this.showDangerTypeDialog = false;
    },
    //隐患区域
    showDangerArea(index, innerIndex) {
      this.keyObject = {
        index,
        innerIndex,
      };
      this.showDangerAreaDialog = true;
    },
    onDangerAreaCallback(item) {
      if (item) {
        const index = this.keyObject.index;
        const innerIndex = this.keyObject.innerIndex;

        this.List.forEach((item1, idx) => {
          if (index == idx) {
            item1.children.forEach((v, i) => {
              if (i == innerIndex) {
                v.HiddenDangerArea = item.AreaName;
                v.HiddenDangerAreaCode = item.AreaCode;
                v.HiddenDangerAreaType = item.AreaType;
                v.HiddenDangerAreaNo = item.AreaNo;

                v.CorrectiveDeptCode = item.CorrectiveDeptCode;
                v.CorrectiveDeptName = item.CorrectiveDeptName;
                v.CorrectiveUserName = item.CorrectiveUserName;
                v.CorrectiveChnName = item.CorrectiveChnName;
              }
            });
          }
        });
      }
      this.showDangerAreaDialog = false;
    },
    ClearCheckTaskTemplateDetails(){
      this.$axios.get('DangerCheckTaskDetailJG/ClearTemporaryDanger?ctCode='+this.ctCode+"&tCode="+this.tCode).then(()=>{
        this.getDetail()
      })
    },
    showDeprtartmentUser(index, innerIndex) {
      this.keyObject = {
        index,
        innerIndex,
      };
      if (this.isSimple) {
        this.showUserChooseDialog = true;
      } else {
        this.showDepartmentAndUserDialog = true;
      }
    },

    // 选择部门人回调
    onUserCallback(item) {
      const index = this.keyObject.index;
      const innerIndex = this.keyObject.innerIndex;

      this.List.forEach((item1, idx) => {
        if (index == idx) {
          item1.children.forEach((v, i) => {
            if (i == innerIndex) {
              if (this.isSimple) {
                v.CorrectiveUserName = item[0].code || "";
                v.CorrectiveChnName = item[0].name || "";
              } else {
                v.CorrectiveDeptName = item.OrgName || "";
                v.CorrectiveDeptCode = item.OrgCode || "";
                v.CorrectiveUserName = item.UserName || "";
                v.CorrectiveChnName = item.ChnName || "";
              }
            }
          });
        }
      });
      this.showDepartmentAndUserDialog = false;
      this.showUserChooseDialog = false;
    },
  },
};
</script>
<style lang="less" scoped>
.total-count {
  display: flex;
  align-items: center;
}
</style>
<style lang="less" scoped>
.check-list {
  min-height: 100vh;
  padding-bottom: 100px;
  background-color: #e8f1f8;
}
.checklist-title {
  display: flex;
  align-items: center;
}
.title-logo {
  width: 15px;
  height: 16px;
  margin-right: 10px;
}
// 符合按钮
.accord-btns {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .accord-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 30%;
    height: 22px;
    background-color: #fff;
    color: #666;
    font-size: 12px;
  }
  .active {
    background-color: #1989fa;
    color: #fff;
  }
  .inconformity {
    background-color: #ee0a24;
    color: #fff;
  }
  .not-applicable {
    background-color: #ff976a;
    color: #fff;
  }
}
.inconformity-list {
  background-color: #fff;
  margin-top: 10px;
  padding-top: 10px;
}
/*
        .main {
            height: 100vh;
        }
    */

.det_top_box {
  padding: 10px;
  background-color: #e8f1f8;
}

.detail_header {
  color: #ffffff;
  background: url("../../../assets/Images/AppIcon/image_riskunit_detail_bg.png");
  background-size: cover;
  padding: 10px;
  border-radius: 5px;
  /*background-color: #fff;*/

  .det_top {
    display: flex;
    justify-content: space-between;

    .dep_top_img {
      height: 20px;
      width: 20px;
      margin-right: 5px;
    }
  }

  .det_name {
    margin-top: 20px;
    text-align: center;
  }

  .det_location {
    text-align: center;
    margin-bottom: 20px;
  }
}
.det_tab {
  padding: 10px;
  .det_tab_item {
    padding: 10px 0;
    background-color: #fff;
    border-radius: 5px;
    margin-bottom: 10px;

    .det_tab_item_text {
      padding: 0 10px;
    }
  }
}

.text_box {
  padding: 10px;
  border-radius: 5px;
  /*background-color: #e8f1f8;*/
  margin-bottom: 10px;

  .text_top {
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    .top_link {
      color: #1989fa;
    }
  }

  .text_item {
    display: flex;
    justify-content: space-between;
    margin-left: 10px;

    .item_link {
      color: #1989fa;
    }
  }

  .text_img {
    display: flex;
    align-items: center;

    .img_item {
      width: 33.3%;
      text-align: center;

      img {
        height: 25px;
        width: 25px;
        margin-bottom: 10px;
      }
    }
  }

  .text_history {
    display: flex;
    vertical-align: middle;
    margin-bottom: 10px;
  }

  .text_member {
    color: #1989fa;
    margin-bottom: 10px;
  }

  .text_total_img {
    display: flex;
    align-items: center;

    .img_item {
      width: 33.3%;
      text-align: center;

      .img_item_top {
        display: flex;
        vertical-align: middle;
        margin-bottom: 10px;
      }
      img {
        height: 15px;
        width: 15px;
        margin-right: 5px;
      }
    }
  }
  .text_record_list {
    .list_row {
      display: flex;
      justify-content: space-between;
      margin-bottom: 10px;
      > div {
        width: 33.3%;
      }
      .row_center {
        text-align: center;
      }
      .row_right {
        text-align: right;
      }
    }
  }
}
.operate_det {
  background-color: #fff;
  padding: 10px;
  .operate_list {
    border: 1px solid #e8f1f8;
    .operate_row_first {
      padding: 10px;
      background-color: #e8f1f8;
      border-bottom: 1px solid #e8f1f8;
      margin-bottom: 10px;
    }
    .operate_row {
      padding: 10px;
      border-bottom: 1px solid #e8f1f8;
      /*margin-bottom: 10px;*/
    }
  }
}

.bottom-buttons {
  width: 100%;
  position: fixed;
  bottom: 0;
  left: 0;
  .submit-button,
  .save-btn {
    border: none;
    border-radius: 0;
  }
  .submit-button {
    width: 70%;
  }
  .save-btn {
    width: 33.33%;
  }
}
.van-divider {
  margin-top:10px !important;
  margin-bottom:10px !important;
  border-color: #ccc;
}
</style>

<style lang="less">
.check-list {
  .van-collapse {
    .van-collapse-item__content {
      background-color: #e8f1f8;
      padding: 10px 10px 0px 10px;
    }
  }
}
.check-sum {
  position: fixed;
  top: 45px;
  left: 0px;
  width: 100%;
  z-index: 1000;
}

.check-content {
  margin-top: 45px;
}
</style>
